<template>
  <div class="app-container">
    <div class="tag-wapper">
      <el-card class="info-card">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <el-row class="info-line" :gutter="20">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">名称:</span>
            {{ baseInfo.name }}
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">站点:</span>
            {{ baseInfo.site }}
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">应用:</span>
            {{ biz[baseInfo.biz] }}
          </el-col>
        </el-row>
        <el-row class="info-line" :gutter="20">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">录入时间:</span>
            {{ baseInfo.createdAt }}
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">更新时间:</span>
            {{ baseInfo.updatedAt }}
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="6">
            <span class="detail-tit">子树数量:</span>
            {{ Array.isArray(baseInfo.subTree) ? baseInfo.subTree.length : 0 }}
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>标签树结构</span>
        </div>
        <div>
          <el-tree
            :props="props"
            :load="loadNode"
            lazy
            @node-click="handleNode"
          >
            <!-- <div slot-scope="{ node, data }"> -->
            <!-- <tree-node :data-node="node" /> -->
            <!-- </div> -->
          </el-tree>
        </div>
      </el-card>
    </div>
    <el-dialog title="详情" :visible.sync="visible" @close="closeAddModal">
      <div class="tag_modal">
        <div class="tag_line">
          <div class="tag_item"><span>ID:</span>{{ treeDetail.id }}</div>
          <div class="tag_item"><span>名称:</span>{{ treeDetail.name }}</div>
          <div v-if="treeDetail.parentId !== undefined" class="tag_item">
            <span>父级ID:</span>{{ treeDetail.parentId }}
          </div>
          <div v-else class="tag_item">
            <span>所在树ID:</span>{{ treeDetail.treeId }}
          </div>
        </div>
        <div class="tag_line">
          <div class="tag_item"><span>站点:</span>{{ treeDetail.site }}</div>
          <div class="tag_item"><span>业务名称:</span>{{ treeDetail.biz }}</div>
          <div class="tag_item">
            <span>创建时间</span>{{ treeDetail.createdAt }}
          </div>
        </div>
        <div class="tag_line">
          <div class="tag_item">
            <span>修改时间:</span>{{ treeDetail.updatedAt }}
          </div>
          <div v-if="treeDetail.treeId !== undefined" class="tag_item">
            <span>是否上架:</span>{{ treeDetail.onShelve ? "是" : "否" }}
          </div>
        </div>
      </div>
      <div class="tag_lists">
        <div class="tag_main">
          <el-tag v-for="item in tagLists" :key="item.id" effect="plain">
            {{ item.name }}
          </el-tag>
        </div>
        <el-pagination
          :current-page.sync="treeDetail.tags.pageNum"
          :page-size="treeDetail.tags.pageSize"
          layout="prev, pager, next, jumper"
          :total="treeDetail.tags.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-dialog
        width="400px"
        :title="`新增${['标签树', '标签'][addType - 1]}`"
        :visible.sync="createVisible"
        append-to-body
      >
        <el-form ref="createForm" :model="createForm" :rules="rules">
          <el-row>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="21">
              <el-form-item label="名称" prop="name" label-width="90px">
                <el-input v-model="createForm.name" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="21">
              <el-form-item label="父标签树id" label-width="90px">
                <el-input v-model="createForm.id" disabled autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col
              v-if="addType === 2"
              :xs="24"
              :sm="24"
              :md="12"
              :lg="12"
              :xl="21"
            >
              <el-form-item label="是否发布" label-width="90px">
                <el-switch v-model="createForm.onShelve" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd">提交</el-button>
        </div>
      </el-dialog>

      <div
        v-if="treeDetail.parentId !== undefined"
        slot="footer"
        class="dialog-footer"
      >
        <el-button type="primary" @click="handleAdd(1)">新增子树</el-button>
        <el-button type="primary" @click="handleAdd(2)">新增标签</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import TreeNode from '@/components/TreeNode.vue'
import { getTagTreeDetail, createTag, createTagTree } from "@/api/tag";
export default {
  // components: { TreeNode },
  data() {
    return {
      loaded: false,
      ids: "",
      asyncGetDetail: "",
      baseInfo: {
        name: "",
        subTree: [],
      },
      infoTree: [],
      biz: {
        PGC: "麻雀分发平台",
        CMS: "采编发系统",
        HJ: "行家系统",
      },
      props: {
        label: "name",
        children: "subTree",
        isLeaf: "isLeaf",
      },
      visible: false,
      createVisible: false,
      addType: 0,
      node: "",
      treeDetail: {
        tags: {
          content: [],
        },
      },
      createForm: {
        id: "",
        name: "",
        onShelve: false,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入标签树名称",
            trigger: "blur",
          },
        ],
      },
      queryData: {
        ids: "",
        pageNum: 1,
        pageSize: 40,
      },
      tagLists: [],
    };
  },
  watch: {
    "queryData.ids": {
      handler(val) {
        this.queryData.pageNum = 1;
        this.pageSize = 40;
      },
      immediate: true,
    },
  },
  created() {
    this.ids = this.$route.params.id;
    this.queryData.ids = this.$route.params.id;
  },
  mounted() {},
  methods: {
    loadNode(node, resolve) {
      console.log(node.level, node.data);
      if (node.level === 0) {
        this.rootNode = node;
        this.rootResolve = resolve;
        this.getInfo().then((res) => {
          this.baseInfo = res;
          this.infoTree.push(res);
          resolve(this.infoTree);
        });
      } else {
        console.log("进入");
        this.resovleSubNode(node, resolve);
      }
    },
    getInfo() {
      if (this.loaded) return;
      const loading = this.$loading({
        text: "加载中...",
      });
      return new Promise((resovle, reject) => {
        getTagTreeDetail(this.queryData)
          .then((res) => {
            this.loaded = false;
            loading.close();
            if (res.id) {
              resovle(res);
            } else {
              this.$message.error({
                message: "信息加载失败",
              });
              this.loaded = false;
              loading.close();
              reject();
            }
          })
          .catch((err) => {
            console.log("err", err);
            this.$message.error({
              message: "信息加载失败",
            });
            this.loaded = false;
            loading.close();
            reject();
          });
      });
    },
    resovleSubNode(node, resovle) {
      const tempArr = [];
      // Array.isArray(node.data.tags.content) &&
      // 		node.data.tags.content.forEach((item) => {
      // 		  const tempObj = JSON.parse(JSON.stringify(item))
      // 		  tempObj.subTree = []
      // 		  tempObj.isLeaf = true
      // 		  tempArr.push(tempObj)
      // 		})
      node.data.subTree.forEach((item) => {
        const tempObj = JSON.parse(JSON.stringify(item));
        tempObj.isLeaf = !item.subTree.length;

        tempArr.push(tempObj);
      });
      console.log("tempObj", tempArr);
      resovle(tempArr);
    },
    handleSizeChange() {},
    handleCurrentChange(e) {
      console.log("eeeeeee", e);
      this.queryData.pageNum = e;
      this.getInfo().then((res) => {
        console.log("res", res);
        this.tagLists = [];
        setTimeout(() => {
          this.tagLists = res.tags.content;
        }, 300);
      });
    },
    handleNode(obj, node, self) {
      this.node = node;
      this.treeDetail = obj;
      this.tagLists = obj.tags.content;
      this.visible = true;
    },
    handleAdd(type) {
      this.addType = type;
      this.createVisible = true;
      this.createForm.id = this.treeDetail.id;
    },
    handleDel() {},
    submitAdd() {
      if (this.loaded) return;
      this.$refs.createForm.validate((res) => {
        if (res) {
          this.loaded = true;
          const loading = this.$loading({
            text: "提交中...",
          });
          let asynFn = "";
          const data = JSON.parse(JSON.stringify(this.createForm));
          console.log("datadatadatadata", data);
          if (this.addType === 1) {
            asynFn = createTagTree;
            data.parentId = data.id;
            delete data.onShelve;
          } else {
            asynFn = createTag;
            data.treeId = data.id;
          }
          delete data.id;
          asynFn(data)
            .then((res) => {
              console.log("resresres", res);
              const isSuccess = !isNaN(parseInt(res));
              this.$message({
                type: isSuccess ? "success" : "error",
                message: `提交${isSuccess ? "成功" : "失败"}`,
              });
              if (isSuccess) {
                this.rootNode.childNodes = [];
                this.loaded = false;
                this.loadNode(this.rootNode, this.rootResolve);
                this.visible = false;
                this.createVisible = false;
                this.closeAddModal();
              } else {
                throw new Error("提交失败");
              }
            })
            .catch((err) => {
              this.$message.error({
                message: "提交失败，请重新提交~",
              });
              console.log("error", err);
            })
            .finally(() => {
              loading.close();
              this.loaded = false;
            });
        }
      });
    },
    closeAddModal() {
      this.createForm = {
        id: "",
        name: "",
        onShelve: false,
      };
      this.treeDetail = {
        tags: {
          content: [],
        },
      };
      this.tagLists = [];
      this.addType = 0;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  overflow-x: scroll;
}
.tag-wapper {
  .info-card {
    max-width: 100vw;
    margin-bottom: 30px;
    .info-line {
      & + .info-line {
        margin-top: 16px;
      }
      .detail-tit {
        width: 70px;
        display: inline-block;
        color: #999;
        text-align: right;
        margin-right: 6px;
      }
    }
  }
  .box-card {
    ::v-deep .el-tree-node__label {
      font-size: 16px;
    }
    ::v-deep .el-tree-node__content {
      height: 36px;
    }
  }
}
.tag_modal {
  padding-bottom: 20px;
  .tag_line {
    display: flex;
    justify-content: flex-start;
    & + .tag_line {
      margin-top: 10px;
    }
    .tag_item {
      width: 33.333%;
      font-size: 16px;
      span {
        display: inline-block;
        width: 80px;
        text-align: right;
        margin-right: 10px;
        color: #999;
      }
    }
  }
}
.tag_lists {
  .tag_main {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;

    ::v-deep .el-tag {
      margin-right: 10px;
      margin-top: 10px;
    }
  }
}
::v-deep .el-dialog__body {
  padding-bottom: 10px;
}
::v-deep .el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
